/**
 * Alibaba.com.cn Inc.
 * Copyright (c) 2004-2021 All Rights Reserved.
 */
package com.starlink.common.strategy.paynotify;

import com.starlink.common.domain.BaseEntity;
import com.starlink.common.enums.AcquireModeEnum;
import com.starlink.common.enums.ActionTypeEum;
import com.starlink.common.enums.OrderTypeEnum;
import com.starlink.common.strategy.IPayNotify;
import com.starlink.common.utils.AssertUtil;
import com.starlink.context.SessionContext;
import com.starlink.model.domain.OtherOrderDO;
import com.starlink.model.domain.SchoolbagOrderDO;
import com.starlink.model.domain.UserDO;
import com.starlink.model.request.PointsAcquireBillRequest;
import com.starlink.model.request.mall.WechatPay;
import com.starlink.model.request.mall.WechatRefund;
import com.starlink.model.vo.OtherOrderVO;
import com.starlink.model.vo.UserVO;
import com.starlink.service.PointsService;
import com.starlink.service.SchoolbagOrderReadRecordService;
import com.starlink.service.SchoolbagOrderService;
import com.starlink.service.UserService;
import com.starlink.utils.FastJsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.Objects;

import static com.starlink.common.enums.ActionTypeEum.STAR_PAINT_ACTIVITY_CANCEL;

/**
 * @author zhanghong
 * @version SchoolbagPayNotify.java, v 0.1 2024/4/11 23:02 下午 SchoolbagPayNotify Exp $$
 */
@Slf4j
@Component
public class SchoolbagPayNotify implements IPayNotify {

    @Autowired
    private SchoolbagOrderService schoolbagOrderService;
    @Autowired
    private PointsService pointsService;
    @Autowired
    private UserService userService;

    @Override
    public boolean supports(Integer orderType) {
        return orderType.equals(OrderTypeEnum.SCHOOLBAG.getType());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void handle(WechatPay wechatPay) {
        SchoolbagOrderDO schoolbagOrderDO = schoolbagOrderService.lambdaQuery().eq(SchoolbagOrderDO::getId, wechatPay.getOrderId()).last("limit 1").one();
        AssertUtil.assertNotNull(schoolbagOrderDO, "订单不存在");
        AssertUtil.assertTrue(schoolbagOrderDO.getOrderStatus() == 1, "订单状态不是待支付");
        if (schoolbagOrderDO.getOrderStatus() != 1) {
            log.info("书包订单支付幂等校验 schoolbagOrderDO = {}", FastJsonUtils.toJSONString(schoolbagOrderDO));
            return;
        }
        UserDO orderUser = userService.getById(schoolbagOrderDO.getCreateUser());
        AssertUtil.assertNotNull(orderUser, "订单用户不存在");

        // 更新订单数据和状态
        schoolbagOrderService.lambdaUpdate()
                .set(SchoolbagOrderDO::getWxOrderNo, wechatPay.getWeChatOrderId())
                .set(SchoolbagOrderDO::getOrderStatus, 2)
                .set(SchoolbagOrderDO::getPayTime, new Date())
                .eq(BaseEntity::getId, schoolbagOrderDO.getId())
                .update();

        // 赠送积分
        if (Objects.nonNull(orderUser.getReferrerUserId()) && Objects.nonNull(userService.getById(orderUser.getReferrerUserId()))) {
            // 给邀请人赠送
            pointsService.addPoint(PointsAcquireBillRequest.builder()
                    .userId(orderUser.getReferrerUserId())
                    .title(ActionTypeEum.INVITER_SCHOOLBAG_BUG.getType())
                    .acquireMode(AcquireModeEnum.XIAO_FEI.getType())
                    .acquirePoint(schoolbagOrderDO.getOrderAmount().intValue())
                    .build());
            // 给下单人赠送
            pointsService.addPoint(PointsAcquireBillRequest.builder()
                    .userId(orderUser.getId())
                    .title(ActionTypeEum.PLACE_ORDER_AND_CONSUME.getType())
                    .acquireMode(AcquireModeEnum.XIAO_FEI.getType())
                    .acquirePoint(schoolbagOrderDO.getOrderAmount().intValue())
                    .build());
        }
        // 异步执行编组
        try {
            schoolbagOrderService.joinGroup(schoolbagOrderDO.getId());
        } catch (Exception e) {
            log.error("handle - 书包订单支付回调业务处理异常 wechatPay={}, errorMessage={}", FastJsonUtils.toJSONString(wechatPay), e.getMessage(), e);
        }
    }

    @Override
    public void refundHandle(WechatRefund wechatPay) {
        //TODO 书包订单退款回调处理逻辑(线下退款)
    }
}
